import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import Cookie from '@/plugins/js-cookie'
import piniaStore from '@/store'
export function useSso() {
  const tokenKey = import.meta.env.VITE_SSO_TOKEN_KEY
  const NameKey = import.meta.env.VITE_SSO_NAME
  const loginUrl = import.meta.env.VITE_SSO_LOGIN_PAGE
  const token = Cookie.get(tokenKey)
  const username = Cookie.get(NameKey)
  const router = useRouter()
  const route = useRoute()
  const isError = ref(false)
  const errMsg = ref('')

  const initLogin = async () => {
    const host = window.location.host
    const protocol = window.location.protocol + '//'
    const url = protocol + host
    const redirect = (route.query.redirect as string) || '/'
    console.log('token', token, username)

    if (token && username) {
      // 携带token username去服务器验证
      const clientSetting = {
        username,
        password: token,
      }
      piniaStore.userStore
        .handleLogin(clientSetting)
        .then(() => {
          router.push(redirect)
        })
        .catch((err) => {
          isError.value = true
          errMsg.value = err.error_description
        })
    } else {
      window.location.replace(
        loginUrl + '?redirectUrl=' + url + '/#' + redirect,
      )
    }
  }

  return {
    initLogin,
    isError,
    errMsg,
  }
}
